package com.nhh.v.controller;

import com.nhh.exception.ServiceException;
import com.nhh.v.cons.ServerCons;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import reactor.core.publisher.Mono;

import java.util.stream.Collectors;

/**
 * Created by ywp on 2018/9/3.
 */
@Slf4j
@RestControllerAdvice
public class BaseController {

    @ExceptionHandler(Exception.class)
    public Mono serverExceptionHandler(Exception ex) {
        log.error(ex.getMessage(), ex);

        if (ex instanceof WebExchangeBindException) {//参数校验错误
            WebExchangeBindException se = (WebExchangeBindException) ex;
            String errorMsg = se.getFieldErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
            return Mono.justOrEmpty(ErrorResult.builder().retCode(ServerCons.defaultErrorCode()).retMsg(errorMsg).build());
        }
        if (ex instanceof ServiceException) {//业务错误
            ServiceException se = (ServiceException) ex;
            return Mono.justOrEmpty(ErrorResult.builder().retCode(se.getCode()).retMsg(se.getMessage()).build());
        }
        return Mono.just(ErrorResult.builder().retCode(ServerCons.defaultErrorCode()).retMsg(ex.getMessage()).build());
    }
}


@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
class ErrorResult {
    private String retCode;
    private String retMsg;

}

